package com.rapig.mail.biz;

import java.awt.MenuItem;

import javax.mail.Flags;
import javax.mail.Flags.Flag;
import javax.mail.Message;
import javax.mail.MessagingException;

import com.rapig.mail.bean.MailAccount;

public class MailTask implements Runnable {

	public static boolean running = false;
	public static int tick = 180;
	public static int tickFull = 180;

	@Override
	public void run() {
		if (running) {
			return;
		}
		running = true;
		while (true) {
			tick++;
			if (tick < tickFull) {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
				}
			} else {
				tick = 1;
				process();
			}
		}
	}

	public static void refresh() {
		tick = tickFull;
	}

	public void process() {
		int total = 0;

		StringBuffer info = new StringBuffer();
		for (MailAccount item : MailBIZ.accounts) {
			if (item == null) {
				continue;
			}
			Message[] msgs = MailBIZ.list(item, 1, 10);
			if (msgs == null) {
				continue;
			}

			System.out.println(item.getName());
			int num = 0;
			for (Message message : msgs) {
				if (message == null) {
					continue;
				}

				try {
					Flags f = message.getFlags();
					if (!f.contains(Flag.SEEN)) {
						num = num + 1;
					}
				} catch (MessagingException e) {
				}
			}

			total = total + num;
			for (int i = 0; i < TrayBIZ.mailMenu.getItemCount(); i++) {
				MenuItem mi = TrayBIZ.mailMenu.getItem(i);
				if (mi == null) {
					continue;
				}
				String label = mi.getLabel();
				if (label.startsWith(item.getName())) {
					String newL = item.getName();
					if (num > 0) {
						newL = newL + "(+" + num + ")";
						info.append(newL);
						info.append("\r\n");
					}
					mi.setLabel(newL);
				}
			}
		}

		TrayBIZ.resetTray(total, info.toString());
	}

}
